package com.siping.并发.练习题;

import java.util.concurrent.CyclicBarrier;

/**
 * @author Yang Xu
 * @date 2021/9/6 11:32
 * @description: 可以用于多线程计算数据，最后合并计算结果的场景。
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(5, () -> System.out.println(Thread.currentThread().getName() + "完成所有任务"));
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + " 到达栅栏 A");
                    barrier.await();
                    System.out.println(Thread.currentThread().getName() + " 冲破栅栏 A");

                    Thread.sleep(2000);
                    System.out.println(Thread.currentThread().getName() + " 到达栅栏 B");
                    barrier.await();
                    System.out.println(Thread.currentThread().getName() + " 冲破栅栏 B");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
